<template>
  <div>
    <!-- <div v-if="sendTaskStarted" class="flex flex-row-reverse">
              <span>
                <i class="el-icon-top text-blue-500 text-6xl ml-22" />
                <div class="text-dark-200">
                  邮件发送任务已加入后台，可以关闭此页面，请勿关闭客户端
                </div>
              </span>
            </div> -->
    <div class="text-left">
      <el-dropdown
        class="ml-2.5"
        size="mini"
        split-button
        type="primary"
        @command="(cmd) => handleRandomSelect && handleRandomSelect(cmd)"
        @click="handleRandomSelect && handleRandomSelect('sent')"
      >
        随机选择(发送成功的数据)
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="unsent">发送失败的数据</el-dropdown-item>
          <el-dropdown-item command="read">已经阅读的数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <span class="text-gray-400 ml-2.5"
        >* 随机选择发送账号，随机选择对应状态的收件账号，随机选择邮件内容</span
      >
    </div>
    <el-divider></el-divider>
    <div style="margin: 0px 0px 20px 10px">
      <span style="padding-right: 100px">
        <el-button
          v-if="sendPercent >= 100"
          v-waves
          class="filter-item w-37.5 mr-25"
          type="success"
          size="mini"
          plain
          @click="resetStartButton"
          >任务结束({{ countdown }}s)</el-button
        >
        <template v-else>
          <el-button
            v-if="!isRunning"
            v-waves
            class="filter-item w-37.5 mr-25"
            type="primary"
            icon="el-icon-caret-right"
            size="mini"
            @click="submitFreeSend"
            >{{ $t('email.start') }}</el-button
          >
          <template v-else>
            <el-button
              v-if="isStopped"
              v-waves
              class="filter-item w-37.5 mr-25"
              type="primary"
              icon="el-icon-video-play"
              size="mini"
              @click="resume"
              >继续</el-button
            >
            <el-button
              v-else
              v-waves
              class="filter-item w-37.5 mr-25"
              type="primary"
              icon="el-icon-video-pause"
              size="mini"
              @click="pause"
              >暂停</el-button
            >
          </template>
          <el-button
            v-waves
            class="filter-item w-37.5"
            type="danger"
            icon="el-icon-switch-button"
            size="mini"
            @click="cancelTask"
            :disabled="!isRunning"
            >{{ $t('email.stop') }}</el-button
          >
        </template>
      </span>
    </div>
    <el-divider></el-divider>
    <div>
      <el-form ref="form" :model="form" label-width="380px">
        <div class="flex align-middle text-center items-center justify-center">
          <span class="mr-3">完成进度</span>
          <el-progress
            class="w-200 leading-8"
            :text-inside="true"
            :stroke-width="24"
            :percentage="sendPercent"
            status="success"
            disabled
          ></el-progress>
        </div>
        <el-form-item>
          <span class="ml-65">{{
            $t('email.emailSendSummary', [totalCount, sendCount, failedCount])
          }}</span>
        </el-form-item>
      </el-form>
    </div>
    <el-divider></el-divider>
    <Log ref="log" />
  </div>
</template>
<script>
import moment from 'moment'
import { EmailModule } from '@/store/modules/email'
import { RunningEmailTaskModule } from '@/store/modules/runningEmailTask'

import { getAction, postAction } from '@/api/common'
import Log from './log.vue'
export default {
  name: 'StartSend',
  components: {
    Log,
  },
  props: {
    handleRandomSelect: {
      type: Function,
      default: () => {},
    },
    form: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      sendTaskStarted: false,
      messages: [],
      countdown: 0,
      countdownTimer: null,
    }
  },
  created() {
    this.sendTaskStarted = false
    VUE.$on('Test', this.handleTestEvent)
    VUE.$on('LogSendEmail', this.handleLogEvent)
  },
  beforeDestroy() {
    VUE.$off('Test', this.handleTestEvent)
    VUE.$off('LogSendEmail', this.handleLogEvent)
  },
  computed: {
    sendCount() {
      return RunningEmailTaskModule.inner.sendCount || 0
    },
    failedCount() {
      return RunningEmailTaskModule.inner.failedCount || 0
    },
    totalCount() {
      return RunningEmailTaskModule.inner.totalCount || 0
    },
    isRunning() {
      return !!RunningEmailTaskModule.inner.id
    },
    isStopped() {
      console.log(this.$store.state.runningEmailTask, RunningEmailTaskModule)
      return RunningEmailTaskModule.inner.isStopped
    },
    sendPercent() {
      if (!this.totalCount) return 0
      const result = parseInt((this.sendCount / this.totalCount) * 100)
      if (result >= 100 && !this.countdownTimer) {
        this.countdown = 5
        this.countdownTimer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(this.countdownTimer)
            this.countdownTimer = null
            this.resetStartButton()
          }
        }, 1000)
      }
      return result
    },
  },
  methods: {
    handleTestEvent(res) {
      let sender = EmailModule.receivers.find(
        (r) => r.email === res.ReceiverEmail
      )
      if (res.State === 1 && sender) {
        sender.sendNum = (sender.sendNum || 0) + 1
        EmailModule.SET_RECEIVERS([...EmailModule.receivers])
      }
    },
    handleLogEvent(res) {
      this.$refs.log.push_msg(res)
    },
    /**
     * 获取当前时间
     * format=1精确到天
     * format=2精确到分
     ***/
    getCurrentDate(format) {
      const now = new Date()
      const year = now.getFullYear() // 得到年份
      let month = now.getMonth() // 得到月份
      let date = now.getDate() // 得到日期
      const day = now.getDay() // 得到周几
      let hour = now.getHours() // 得到小时
      let minu = now.getMinutes() // 得到分钟
      let sec = now.getSeconds() // 得到秒
      month = month + 1
      if (month < 10) month = '0' + month
      if (date < 10) date = '0' + date
      if (hour < 10) hour = '0' + hour
      if (minu < 10) minu = '0' + minu
      if (sec < 10) sec = '0' + sec
      let time = ''
      // 精确到天
      if (format === 1) {
        time = year + '-' + month + '-' + date
      } else if (format === 2) {
        // 精确到分
        time = year + month + date + hour + minu + sec
      }
      return time
    },
    /// ///////////////////////////开始发送/////////////////////////////////
    submitFreeSend() {
      // 检测每一个步骤的值是否缺省
      // 检测发送账号
      this.sendTaskStarted = false
      let addresser = this.form.Addresser.filter((a) => a.state === 'SUCCESS')
      let addressee = this.form.Addressee.filter((a) => a.valid !== 2)
      if (addresser.length === 0) {
        this.$message({
          message: this.$t('email.checkField', [
            this.$t('email.senderAccount'),
          ]),
          type: 'warning',
        })
        return false
      }
      // 检测收件列表
      if (addressee.length === 0) {
        this.$message({
          message: this.$t('email.checkField', [this.$t('email.receivers')]),
          type: 'warning',
        })
        return false
      }
      // 检测编辑邮件
      if (this.form.selectedTemplates.length === 0) {
        this.$message({
          message: this.$t('email.checkField', [this.$t('email.editEmail')]),
          type: 'warning',
        })
        return false
      }
      let data = {
        ...this.form,
        Title: this.form.Title + '_' + this.getCurrentDate(2),
        emailTemplateIds: JSON.stringify(
          this.form.selectedTemplates.map((t) => t.id)
        ),
        Addresser: addresser.map((a) => a.id.toString()),
        Addressee: addressee,
      }
      // 检测开始发送的参数
      postAction(data, 'EmailMarketing/Create').then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: this.$t('email.createEmailMarketingSuccessfully'),
            type: 'success',
          })
          VUE.$emit('clientSendCreated')
          this.sendTaskStarted = true
          // return false
        } else {
          this.$message({
            message: this.$t('email.createEmailMarketingFailed'),
            type: 'warning',
          })
        }
      })
      // this.$message({message: '发送成功',type: 'success'})
    },
    resume() {
      this.$common.ExeInvoke((proxy) => {
        RunningEmailTaskModule.ResumeSendTask()
        proxy.ResumeSendEmail()
      })
    },
    pause() {
      this.$common.ExeInvoke((proxy) => {
        RunningEmailTaskModule.PauseSendTask()
        proxy.PauseSendEmail()
      })
    },
    cancelTask() {
      this.$common.ExeInvoke((proxy) => {
        proxy.AbortSendEmail()
        getAction(
          {},
          `EmailMarketing/CancelEmailMarketingTask?id=${RunningEmailTaskModule.inner.id}`
        )
          .then(() => {
            // this.$message({
            //   message: this.$t('email.taskCanceled'),
            //   type: 'success',
            // })
          })
          .then(() => {})
          .finally(() => {
            VUE.$emit('clientSendCreated')
          })
      })
    },
    resetStartButton() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
      RunningEmailTaskModule.NEW_RUNNING_EMAIL_TASK({
        id: 0,
        totalCount: 0,
        sendCount: 0,
      })
    },
  },
  components: { Log },
}
</script>
